package com.dmxh.service.impl;

import com.dmxh.api.UserAPI;
import com.dmxh.mapper.TbAddressMapper;
import com.dmxh.mapper.TbAreasMapper;
import com.dmxh.mapper.TbCitiesMapper;
import com.dmxh.mapper.TbProvincesMapper;
import com.dmxh.pojo.*;
import com.dmxh.service.AddressService;
import com.dmxh.vo.AddressVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private TbAddressMapper tbAddressMapper;
    @Autowired
    private TbProvincesMapper tbProvincesMapper;
    @Autowired
    private TbCitiesMapper tbCitiesMapper;
    @Autowired
    private TbAreasMapper tbAreasMapper;
    @Autowired
    private UserAPI userAPI;

    @Override
    public List<AddressVo> queryAllAddress(String userId) {
        TbUser tbUser = userAPI.queryUserById(Long.valueOf(userId));
        TbAddressExample tbAddressExample = new TbAddressExample();
        tbAddressExample.createCriteria().andUserIdEqualTo(tbUser.getUsername());
        List<TbAddress> tbAddresses = tbAddressMapper.selectByExample(tbAddressExample);
        List<AddressVo> collect = tbAddresses.stream().map(tbAddress -> {
            AddressVo addressVo = new AddressVo();
            BeanUtils.copyProperties(tbAddress, addressVo);
            return addressVo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public AddressVo queryById(long id) {
        TbAddress tbAddress = tbAddressMapper.selectByPrimaryKey(id);
        AddressVo addressVo = new AddressVo();
        BeanUtils.copyProperties(tbAddress,addressVo);
        return addressVo;
    }

    @Override
    public void addInfo(AddressVo addressVo) {
        TbAddress tbAddress = new TbAddress();
        BeanUtils.copyProperties(addressVo, tbAddress);
        tbAddressMapper.insertSelective(tbAddress);
    }

    @Override
    public void updateInfo(AddressVo addressVo) {
        TbAddress tbAddress = new TbAddress();
        BeanUtils.copyProperties(addressVo, tbAddress);
        tbAddressMapper.updateByPrimaryKeySelective(tbAddress);
    }

    @Override
    public void deleteById(long id) {
        tbAddressMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<TbProvinces> queryAllProvince() {
        return tbProvincesMapper.selectByExample(null);
    }

    @Override
    public List<TbCities> queryAllCity() {
        return tbCitiesMapper.selectByExample(null);
    }

    @Override
    public List<TbAreas> queryAllArea() {
        return tbAreasMapper.selectByExample(null);
    }


}
